﻿using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Windows.Forms;

namespace HDM.NexusEngine.Core
{
    public class FastLoop
    {
        [SuppressUnmanagedCodeSecurity]
        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        private static extern bool PeekMessage(out Message msg, IntPtr hWnd, uint messageFilterMin, uint messageFilterMax, uint flags);

        private readonly PreciseTimer _timer = new PreciseTimer();
        public delegate void LoopCallback(double elapsedTime);
        private readonly LoopCallback _callback;

        public FastLoop(LoopCallback callback)
        {
            _callback = callback;
            Application.Idle += OnApplicationEnterIdle;
        }

        void OnApplicationEnterIdle(object sender, EventArgs e)
        {
            while (IsAppStillIdle())
            {
                _callback(_timer.GetElapsedTime());
            }
        }

        private bool IsAppStillIdle()
        {
            Message msg;
            return !PeekMessage(out msg, IntPtr.Zero, 0, 0, 0);
        }
    }
}
